package com.daily.pump.widget.zxing;

import android.content.Context;
import android.hardware.Camera;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.xunxi.mimi.utils.LogUtil;

import cn.bertsir.zbar.ScanCallback;
import cn.bertsir.zbar.utils.QRUtils;

/**
 * Desc:二维码扫描-相机预览view
 * <p>
 * Author: [李豫]
 * Date: 2019-01-02
 * Copyright: Copyright (c) 2010-2018
 * Company: @咪咕动漫
 * Updater:
 * Update Time:
 * Update Comments:
 */
public class CameraPreview extends FrameLayout implements SurfaceHolder.Callback {

    private CameraManager mCameraManager;
    private CameraScanAnalysis mPreviewCallback;
    private SurfaceView mSurfaceView;
    private float mOldDist = 1f;

    public CameraPreview(Context context) {
        this(context, null);
    }

    public CameraPreview(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CameraPreview(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        mCameraManager = new CameraManager(context);
        mPreviewCallback = new CameraScanAnalysis();
    }

    /**
     * Set Scan results callback.
     *
     * @param callback {@link ScanCallback}.
     */
    public void setScanCallback(ScanCallback callback) {
        mPreviewCallback.setScanCallback(callback);
    }

    /**
     * Camera start preview.
     */
    public boolean start() {
        try {
            mCameraManager.openDriver();
        } catch (Exception e) {
            Toast.makeText(getContext(), "摄像头权限被拒绝！", Toast.LENGTH_SHORT).show();
            return false;
        }
        mPreviewCallback.onStart();

        if (mSurfaceView == null) {
            mSurfaceView = new SurfaceView(getContext());
            addView(mSurfaceView, new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

            SurfaceHolder holder = mSurfaceView.getHolder();
            holder.addCallback(this);
            holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }
        startCameraPreview(mSurfaceView.getHolder());
        return true;
    }

    /**
     * Camera stop preview.
     */
    public void stop() {
        removeCallbacks(mAutoFocusTask);
        mPreviewCallback.onStop();

        mCameraManager.stopPreview();
        mCameraManager.closeDriver();
    }

    private void startCameraPreview(SurfaceHolder holder) {
        try {
            mCameraManager.startPreview(holder, mPreviewCallback);
            mCameraManager.autoFocus(mFocusCallback);
        } catch (Exception e) {
            e.printStackTrace();

        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        if (holder.getSurface() == null) {
            return;
        }
        mCameraManager.stopPreview();
        startCameraPreview(holder);
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
    }

    private Camera.AutoFocusCallback mFocusCallback = new Camera.AutoFocusCallback() {
        @Override
        public void onAutoFocus(boolean success, Camera camera) {
            postDelayed(mAutoFocusTask, 1000);
        }
    };

    private Runnable mAutoFocusTask = new Runnable() {
        @Override
        public void run() {
            mCameraManager.autoFocus(mFocusCallback);
        }
    };

    @Override
    protected void onDetachedFromWindow() {
        stop();
        super.onDetachedFromWindow();
    }

    public void setFlash() {
        mCameraManager.setFlash();
    }

    public void setFlash(boolean open) {
        mCameraManager.setFlash(open);
    }

    public void decodeQRcode(String imagePic) {
        try {
            String qrcontent = QRUtils.getInstance().decodeQRcode(imagePic);
            if (!TextUtils.isEmpty(qrcontent)) {
                onScanResult(qrcontent);
            } else {
                //尝试用zxing再试一次
                String qrZxingcontent = QRUtils.getInstance().decodeQRcodeByZxing(imagePic);
                if (!TextUtils.isEmpty(qrZxingcontent)) {
                    onScanResult(qrZxingcontent);
                } else {
                    onScanResult(null);
                }

            }
        } catch (Exception e) {
            onScanResult(null);
        }
    }

    private void onScanResult(String qrcontent) {
        if (mPreviewCallback != null) {
            ScanCallback scanCallback = mPreviewCallback.getScanCallback();
            if (scanCallback != null) {
                scanCallback.onScanResult(qrcontent);
            }
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (mCameraManager == null || !mCameraManager.isOpen()) {
            return super.onTouchEvent(event);
        }
        if (event.getPointerCount() == 2) {
            switch (event.getAction() & MotionEvent.ACTION_MASK) {
                case MotionEvent.ACTION_POINTER_DOWN:
                    mOldDist = calculateFingerSpacing(event);
                    break;
                case MotionEvent.ACTION_MOVE:
                    float newDist = calculateFingerSpacing(event);
                    if (newDist > mOldDist) {
                        handleZoom(true, mCameraManager.getCamera());
                    } else if (newDist < mOldDist) {
                        handleZoom(false, mCameraManager.getCamera());
                    }
                    break;
            }
        }
        return true;
    }

    /**
     * 计算手指间距
     */
    static float calculateFingerSpacing(MotionEvent event) {
        float x = event.getX(0) - event.getX(1);
        float y = event.getY(0) - event.getY(1);
        return (float) Math.sqrt(x * x + y * y);
    }

    /**
     * 处理手动放大缩小
     *
     * @param isZoomIn
     * @param camera
     */
    private static void handleZoom(boolean isZoomIn, Camera camera) {
        if (camera == null) {
            return;
        }
        Camera.Parameters params = camera.getParameters();
        if (params.isZoomSupported()) {
            int zoom = params.getZoom();
            if (isZoomIn && zoom < params.getMaxZoom()) {
                LogUtil.debug(CameraPreview.class, "放大");
                zoom++;
            } else if (!isZoomIn && zoom > 0) {
                LogUtil.debug(CameraPreview.class, "缩小");
                zoom--;
            } else {
                LogUtil.debug(CameraPreview.class, "既不放大也不缩小");
            }
            params.setZoom(zoom);
            camera.setParameters(params);
        } else {
            LogUtil.debug(CameraPreview.class, "不支持缩放");
        }
    }
}